package com.kun.controller.admin;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSONObject;
import com.kun.config.EntityRedisSerializer;
import com.kun.controller.BaseController;
import com.kun.entity.Book;
import com.kun.entity.BorrowRecord;
import com.kun.result.ExceptionMsg;
import com.kun.result.Response;
import com.kun.result.ResponseData;
import com.kun.service.BookService;
import com.kun.service.BorrowService;
import com.kun.service.UserService;

/**
 * @description: 
 * @author: KM
 * 2018年5月9日 下午4:38:14
 */
@Controller
@RequiresAuthentication
@RequestMapping("/admin")
public class BorrowAdminController extends BaseController{
	
	@Autowired
	private BookService  bookServiceImpl;
	
	@Autowired
	private UserService  userServiceImpl;
	
	@Autowired
	private BorrowService borrowService;
	
	@Autowired
    protected RedisTemplate<String, Object> redisTemplate;

	//借阅列表页面
	@RequiresPermissions("borrowInfo:view")
	@RequestMapping("/borrowList")
	public String borrowList(){
		return "admin/borrowList";
	}
	
	//校验取书码页面
	@RequiresPermissions("validateCode:view")
	@RequestMapping("/valCode")
	public String validateCode(){
		return "admin/validateCode";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder, WebRequest request) {
		//转换日期
		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
	}
	
	//借阅列表
	@RequiresPermissions("borrowInfo:view")
	@RequestMapping("/getBorrow")
	@ResponseBody
	public Map<String,Object> getBorrow(@RequestParam(name = "begin") int begin,
			@RequestParam(name = "length") int length,
			String acceptMapJson,String jsonString){
		JSONObject json = JSONObject.parseObject(acceptMapJson);
		Map<String,Object> acceptMap = (Map<String,Object>)json;
		List<String> useridList = new ArrayList<String>();
		List<Integer> bookidList = new ArrayList<Integer>();
		String nickname="",realname="",bookname="",typeid="";
		if(acceptMap!=null&&!acceptMap.isEmpty()){
			nickname = (String)acceptMap.get("nickname");
			realname = (String)acceptMap.get("realname");
			bookname = (String)acceptMap.get("bookname");
			typeid = (String)acceptMap.get("typeid");
		}
		//nickname realname模糊查询出List<userid>
		useridList	= userServiceImpl.selectUserByLikeNicknameOrRealame(nickname,realname);
		//bookname 模糊查询出List<bookid>
		bookidList = bookServiceImpl.selectBookLikeBookName(bookname,typeid);
		Map<String,Object> map = borrowService.selectAllBorrow(begin, length, jsonString,useridList,bookidList);
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("count",map.get("allRecord"));
		m.put("data",map.get("borrowList"));
		m.put("code", 0);
		m.put("msg", "");
		return m;
	}
	
	//校验取书code
	@RequiresPermissions("validateCode:select")
	@RequestMapping(value="/valBookCode",method=RequestMethod.POST)
	@ResponseBody
	public Response validateBookCode(@RequestParam(name = "code") String code){
		redisTemplate.setValueSerializer(new EntityRedisSerializer());
		BorrowRecord borrowRecord = (BorrowRecord)redisTemplate.opsForValue().get(code);
		if(borrowRecord!=null&&"0".equals(borrowRecord.getIsDeal())){
			borrowRecord.setBook(bookServiceImpl.selectBookById(borrowRecord.getBookId()));//存入图书对象
			return new ResponseData(ExceptionMsg.SUCCESS,borrowRecord);
		}else{
			return result(ExceptionMsg.CodeExpire);
		}
	}
	
	//处理订单
	@RequiresPermissions("validateCode:submit")
	@RequestMapping(value="/dealBookCode",method=RequestMethod.POST)
	@ResponseBody
	public Response dealBookCode(@RequestParam(name = "code") String code){
		redisTemplate.setValueSerializer(new EntityRedisSerializer());
		BorrowRecord borrowRecord = (BorrowRecord)redisTemplate.opsForValue().get(code);
		if(borrowRecord!=null&&"0".equals(borrowRecord.getIsDeal())){
			borrowRecord.setIsDeal("1");
			int i = borrowService.updateBorrow(borrowRecord);
			if(i!=0){
				redisTemplate.opsForValue().getOperations().delete(code);//删除code
				return new ResponseData(ExceptionMsg.SUCCESS);
			}
		}
		return result(ExceptionMsg.CodeExpire);
	}
	
	
	//管理员增加借阅记录
	@RequiresPermissions("borrowInfo:add")
	@RequestMapping(value="insertBorrow",method=RequestMethod.POST) 
	@ResponseBody
    public Response insertBorrow(@RequestParam(name = "realname") String realname,@RequestParam(name = "booknumber") String booknumber,
    		@RequestParam(name = "amount") int amount,@RequestParam(name = "borrowTime") int borrowTime,String idCard){
		if(amount<=0){
			return result(ExceptionMsg.FAILED);
		}
		List<String> idList = userServiceImpl.selectUserByRealameAndIdcard(realname, idCard);
		if(idList.size()!=1){
			if(idList.size()==0){
				return result(ExceptionMsg.LoginNameNotExists);//未注册
			}else if(idList.size()>1){
				return result(ExceptionMsg.ExitManyName);//存在同名
			}
		}
		Book book = bookServiceImpl.selectBookByBooknumber(booknumber);
		if(book==null){
			return result(ExceptionMsg.BookNotExit);//不存在该书
		}else if(amount>book.getBookamount()){//数量不足
			return new ResponseData(ExceptionMsg.AmountError,book.getBookamount());
		}
		Date d = new Date();
		String ordersNumber = "TS"; // 初始化订单编号
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = format.format(d);
		int random = new Random().nextInt(100000);
		ordersNumber += formatDate + random;
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.WEDNESDAY, borrowTime);
		
		BorrowRecord br = new BorrowRecord();
		br.setBorrowId(ordersNumber);
		br.setBorrowTime(d);
		br.setReturnTime(c.getTime());
		br.setBookId(book.getBookid());
		br.setUserId(idList.get(0));
		br.setIsDeal("1");
		br.setAmount(amount);
		int i =borrowService.insertBorrow(br);
		if(i>0){
			//减库存  增加图书借阅记录数量
			bookServiceImpl.updateAmountByBookNumber(booknumber, -amount,true);
			return result(ExceptionMsg.SUCCESS);
		}
		return result(ExceptionMsg.FAILED);
	}
	
	//更新借阅记录
	@RequiresPermissions("borrowInfo:update")
	@RequestMapping(value="updateBorrow",method=RequestMethod.POST) 
	@ResponseBody
    public Response updateBorrow(BorrowRecord br,String bookNumber){
		int i = borrowService.updateBorrow(br);
		if(i>0){
			if("2".equals(br.getIsDeal())){//归还 加库存
				int j = bookServiceImpl.updateAmountByBookNumber(bookNumber, br.getAmount(),false);
				if(j<=0){
					return result(ExceptionMsg.FAILED);
				}
			}
			return result(ExceptionMsg.SUCCESS);
		}
		return result(ExceptionMsg.FAILED);
	}
	
	//删除借阅记录
	@RequiresPermissions("borrowInfo:delete")
	@RequestMapping(value="deleteBorrow",method=RequestMethod.POST) 
	@ResponseBody
    public Response deleteBorrow(String borrowId,String isDeal,String bookNumber,int amount){
		int i = borrowService.deleteBorrow(borrowId);
		if(i>0){
			if(!"2".equals(isDeal)){//非归还状态 删除需要回滚库存
				bookServiceImpl.updateAmountByBookNumber(bookNumber, amount, false);
			}
			return result(ExceptionMsg.SUCCESS);
		}
		return result(ExceptionMsg.FAILED);
	}
}
